import { AnyFn } from "@/types";
import { DependencyList, useCallback, useEffect, useRef } from "react";

/**防抖Hook */
export function useDebounce<T extends AnyFn>(fn: T, delay: number, dep: DependencyList = []) {
    const { current } = useRef<{ fn: T, timer: NodeJS.Timeout | null }>({ fn, timer: null });
    useEffect(function () {
        current.fn = fn;//缓存一下
    }, [fn]);
    useEffect(() => {
        return () => {
            if (current.timer) {
                clearTimeout(current.timer);
            }
        }
    }, [])
    return useCallback(function (...args: Parameters<T>) {
        if (current.timer) {
            clearTimeout(current.timer);
        }
        current.timer = setTimeout(() => {
            current.fn(...args);
        }, delay);
    }, dep)
}

/**节流Hook */
export function useThrottle<T extends AnyFn>(fn: T, delay: number, dep: DependencyList = []) {
    const { current } = useRef<{ fn: T, flag: boolean }>({ fn, flag: false });
    useEffect(function () {
        current.fn = fn;
    }, [fn]);
    return useCallback(function (...argu: Parameters<T>) {
        if (current.flag) return
        current.flag = true
        current.fn(argu) //通过剩余参数的形式传递
        setTimeout(() => {//指定时间间隔后关闭节流阀
            current.flag = false
        }, delay);
    }, dep)
} 